package com.egreen.pointsmall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.egreen.common.States;
import com.egreen.common.pojo.DTO.pointsmall.CartUpdateDTO;
import com.egreen.common.pojo.DTO.pointsmall.commitOrderDTO;
import com.egreen.common.pojo.VO.pointsmall.CartVO;
import com.egreen.common.pojo.entity.pointsmall.Cart;
import com.egreen.common.pojo.entity.pointsmall.Orders;
import com.egreen.common.pojo.entity.pointsmall.PointsUser;
import com.egreen.common.pojo.entity.pointsmall.UserAddress;
import com.egreen.pointsmall.exception.PointsmallException;
import com.egreen.pointsmall.service.ICartService;
import com.egreen.pointsmall.service.IUserAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 购物车表 前端控制器
 * </p>
 *
 * @author yyf
 * @since 2023-04-04
 */
@Controller
@RequestMapping("/cart")
@Slf4j
public class CartController {
    @Autowired
    private ICartService cartService;
    @Autowired
    private IUserAddressService userAddressService;

    /**
     * 添加购物车
     * @param productId
     * @param price
     * @param quantity
     * @param session
     * @return
     */
    @GetMapping("/add/{productId}/{price}/{quantity}")
    public String add(
            @PathVariable("productId") Integer productId,
            @PathVariable("price") Float price,
            @PathVariable("quantity") Integer quantity,
            HttpSession session
    ) {
        if (productId == null || price == null || quantity == null) {
            log.info("添加购物车失败");
            throw new PointsmallException(States.PARAMETER_NULL);
        }
        PointsUser pointsUser = (PointsUser) session.getAttribute("user");
        if (pointsUser == null) {
            //表示当前未登录,添加购物车失败
            throw new PointsmallException(States.NOT_LOGIN);
        }
        Cart cart = new Cart();
        cart.setUserId(pointsUser.getId());
        cart.setProductId(productId);
        cart.setQuantity(quantity);
        cart.setCost(quantity * price);
        boolean add = cartService.add(cart);
        if (!add) {
            log.info("添加购物车失败");
            throw new PointsmallException(States.CART_ADD_ERROR);
        }
        return "redirect:/cart/get";
    }

    /**
     * 展示购物车
     */
    @GetMapping("/get")
    public ModelAndView get(HttpSession session) {
        PointsUser user = (PointsUser) session.getAttribute("user");
        if (user == null) {
            throw new PointsmallException(States.NOT_LOGIN);
        }
        List<CartVO> cartVoList = cartService.getCartVoList(user.getId());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("settlement1");
        modelAndView.addObject("cartList", cartVoList);
        return modelAndView;
    }

    /**
     * 更新购物车方法
     *
     * @return
     */
    @PostMapping("/update/{id}/{quantity}/{cost}")
    @ResponseBody
    public String update(
            @PathVariable("id") Integer id,
            @PathVariable("quantity") Integer quantity,
            @PathVariable("cost") Float cost,
            HttpSession session
    ) {
        log.info("id为{}", id);
        PointsUser user = (PointsUser) session.getAttribute("user");
        if (user == null) {
            throw new PointsmallException(States.NOT_LOGIN);
        }
        if (id == null || quantity == null || cost == null) {
            throw new PointsmallException(States.PARAMETER_NULL);
        }
        CartUpdateDTO cartUpdateDTO = new CartUpdateDTO();
        cartUpdateDTO.setId(id);
        cartUpdateDTO.setQuantity(quantity);
        cartUpdateDTO.setCost(cost);
        if (cartService.updateCart(cartUpdateDTO)) {
            return "success";
        }
        return "fail";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id, HttpSession session) {
        if (id == null) {
            throw new PointsmallException(States.PARAMETER_NULL);
        }
        PointsUser user = (PointsUser) session.getAttribute("user");
        if (user == null) {
            throw new PointsmallException(States.NOT_LOGIN);
        }
        if (cartService.delete(id)) {
            return "redirect:/cart/get";
        }
        return null;
    }

    /**
     * 确实订单
     *
     * @param session
     * @return
     */
    @GetMapping("/confirm")
    public ModelAndView confirm(HttpSession session) {
        PointsUser user = (PointsUser) session.getAttribute("user");
        if (user == null) {
            throw new PointsmallException(States.NOT_LOGIN);
        }
        //返回购物车相关数据
        List<CartVO> cartVoList = cartService.getCartVoList(user.getId());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("settlement2");
        modelAndView.addObject("cartList", cartVoList);
        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        modelAndView.addObject("addressList", userAddressService.list(queryWrapper));
        return modelAndView;
    }

    /**
     * 提交订单，将购物车记录删除，转为订单表记录
     * @param userAddress
     * @param session
     * @return
     */
    @PostMapping("/commit")
    public ModelAndView commit(String userAddress,
                               HttpSession session,
                               String address,
                               String remark
    ) {
        if (userAddress == null) {
            throw new PointsmallException(States.PARAMETER_NULL);
        }
        PointsUser user = (PointsUser) session.getAttribute("user");
        if (user == null) {
            throw new PointsmallException(States.NOT_LOGIN);
        }
        commitOrderDTO commitOrderDTO = new commitOrderDTO();
        commitOrderDTO.setUserAddress(userAddress);
        commitOrderDTO.setAddress(address);
        commitOrderDTO.setRemark(remark);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("settlement3");
        Orders order = cartService.commit(commitOrderDTO, user);
        if (order != null) {
            modelAndView.addObject("orders", order);
            modelAndView.addObject("cartList", cartService.getCartVoList(user.getId()));
            return modelAndView;
        }
        return null;
    }
}

